<template>
  <div class="entity-org">
    <div class="mateCascader">
      <el-select :value="organizationId" @change="organizationSelectChange">
        <el-option
          v-for="item in organizationList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </div>
    <div class="entity-main">
      <el-row :gutter="20" type="flex">
        <el-col :span="12">
          <NewCard title="渠道" :isright="true" :border="false">
            <template #right>
              <ComForm title="搜索" @EventOnsubmit="searchRefFn" :list="comForm"></ComForm>
            </template>
            <!-- 表格 -->
            <el-table
              :data="channelList"
              style="width: 100%"
              highlight-current-row
              show-summary
              :summary-method="getSummaries"
              v-hasPermi="['work:commercialManager:placeListAll']"
            >
              <el-table-column label="渠道姓名" width="100">
                <template slot-scope="scope">
                  <!-- <p>{{ scope.row.name }}</p> -->
                  <p
                    v-if="!!scope.row.isName"
                    @dblclick="openEditWorkMail(scope.row, 'name')"
                  >
                    {{ scope.row.name }}
                  </p>
                  <el-input
                    autofocus
                    @blur="editWorkMail(scope.row, 'name')"
                    v-else
                    placeholder="姓名"
                    v-model="scope.row.name"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号">
                <template slot-scope="scope">
                  <!-- <p
                    v-if="!!scope.row.isEditPhonenumber"
                    @dblclick="openEditWorkMail(scope.row, 'phonenumber')"
                  >
                    {{ scope.row.phonenumber }}
                  </p>
                  <el-input
                    autofocus
                    @blur="editWorkMail(scope.row, 'name')"
                    v-else
                    placeholder="请输入姓名"
                    v-model="scope.row.phonenumber"
                  ></el-input>-->
                  <p>{{ scope.row.phonenumber }}</p>
                </template>
              </el-table-column>
              <!-- 上级 -->
              <el-table-column prop="higherLevel" label="上级">
                <template slot-scope="scope">
                  <!-- <el-dropdown
                    @command="
                      (item) => {
                        editHigherLevelNameFn(item, scope.row, true);
                      }"
                    trigger="click"
                    v-hasPermi="['work:commercialManager:edit']"
                  >
                    <span class="el-dropdown-link">
                      {{ getHigherLevelName(scope.row.higherLevel) || "--"
                      }}<i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        :command="item"
                        v-for="item in channelListSuperiorFiter(
                          channelfiler,
                          scope.row
                        )"
                        :key="item.id"
                        >{{ item.name }}</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>-->

                  <!-- 上级选择框 -->
                  <div class="selsect-box">
                    <p>
                      {{scope.row.higherLevelName ? scope.row.higherLevelName : '--'}}
                      <i class="el-icon-caret-bottom"></i>
                    </p>
                    <el-select
                      v-model="scope.row.higherLevel"
                      placeholder="--"
                      v-loadmore="superiorMore"
                      @change="(item) => {
                      editHigherLevelNameFn(item, scope.row, true);
                    }"
                      v-hasPermi="['work:commercialManager:edit']"
                    >
                      <el-option
                        v-for="(item,index) in personnels"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </div>
                  <!-- 上级选择框 end -->
                </template>
              </el-table-column>
              <!-- 上上级 -->
              <el-table-column prop="supervisorId" label="上上级">
                <template slot-scope="scope">
                  <!-- <el-dropdown
                    @command="
                      (item) => {
                        editHigherLevelNameFn(item, scope.row);
                      }
                    "
                    trigger="click"
                    v-hasPermi="['work:commercialManager:edit']"
                  >
                    <span class="el-dropdown-link">
                      {{ getHigherLevelName(scope.row.supervisorId) || "--"
                      }}<i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        :command="item"
                        v-for="item in channelListSuperiorFiter(
                          channelfiler,
                          scope.row
                        )"
                        :key="item.id"
                        >{{ item.name }}</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>-->

                  <!-- 上上级选择框 -->
                  <div class="selsect-box">
                    <p>
                      {{scope.row.supervisorName ? scope.row.supervisorName : '--'}}
                      <i class="el-icon-caret-bottom"></i>
                    </p>
                    <el-select
                      v-model="scope.row.supervisorId"
                      placeholder="--"
                      v-loadmore="superiorMore"
                      @change="(item) => {
                      editHigherLevelNameFn(item, scope.row);
                    }"
                      v-hasPermi="['work:commercialManager:edit']"
                    >
                      <el-option
                        v-for="(item,index) in personnels"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </div>
                  <!-- 上上级选择框 end -->
                </template>
              </el-table-column>
              <el-table-column prop="userCount" label="客户量">
                <template slot-scope="scope">
                  <p>{{ scope.row.userCount }}</p>
                </template>
              </el-table-column>
              <el-table-column width="50" label="状态">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    active-color="#f87a23"
                    active-value="0"
                    inactive-value="1"
                    @change="changeSwitch(scope.row)"
                  ></el-switch>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[10, 20, 30, 40]"
                :pager-count="5"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageing.total"
              ></el-pagination>
            </div>

            <div class="bottomBtn" v-hasPermi="['work:commercialManager:add']">
              <el-button
                v-if="buttonVissible"
                class="button-new-tag"
                size="medium"
                @click="showButton"
              >+ 添加渠道</el-button>
              <div v-else class="inputBox">
                <!-- <el-input
                  v-model="addObj.name"
                  placeholder="请输入名称"
                ></el-input>-->
                <el-input v-model="addObj.phonenumber" placeholder="请输入手机号"></el-input>
              </div>
              <div class="buttonBox">
                <el-button round type="primary" @click="addBusiness">确认</el-button>
                <el-button round @click="addReset">取消</el-button>
              </div>

              <!-- <el-button @click="clickDirector" v-if="directorBtnShow"
          >+添加商务专员
        </el-button>
        <el-input
          v-model="directorBtnValue"
          v-else
          @blur="directorBtnShow = true"
          @keyup.enter.native="addDirector"
          ref="bottBtn"
        >
              </el-input>-->
            </div>
          </NewCard>
        </el-col>
        <el-col :span="12">
          <BusinessList
            v-hasPermi="['work:commercialManager:list']"
            ref="businessList"
            :organizationId="organizationId"
          ></BusinessList>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  getcommercialManagerplaceListAllApi,
  getCommercialManageraddApi,
  getCommercialManagerEditApi
} from "@/wss/newApi_3-24/work/commercialManager.js";
import {
  getPlaceListApi,
  getPlaceGetInfoApi
} from "@/BMViews/api/base/place.js";
import NewCard from "@/wss/components/newCard.vue";
import ComForm from "@/wss/components/comForm.vue";
import ComTable from "@/wss/components/comTable.vue";
import BusinessList from "./businessList.vue";
const arr = [null, "", undefined];

export default {
  name: "EntityOrg",
  props: {
    // 组织列表
    organizationList: {
      type: Array,
      default: []
    },
    // 初始化组织id
    organizationId: {
      type: String,
      default: ""
    }
  },
  components: { NewCard, ComForm, ComTable, BusinessList },
  data() {
    return {
      pageing: { pageNum: 1, pageSize: 10, total: 0 },

      personing: { pageNum: 1, pageSize: 10, total: 0 }, //人员的分页
      personnels: [], //渠道人员列表，显示在上级和上上级那里
      personnelValue: "", //选择的值

      // 是否显示添加渠道按钮
      buttonVissible: true,
      // 添加商务参数
      addObj: {
        organizationId: "",
        // name: "",
        phonenumber: "",
        //类型 1商务 2渠道
        type: "2"
      },
      optionList: [
        { id: "122", title: "三师科技" },
        { id: "123", title: "法通咨询" }
      ],
      // 表单配置
      comForm: {
        modes: [
          {
            formType: "input",
            placeholder: "渠道姓名",
            mode: "name"
          },
          {
            mode: "phonenumber",
            formType: "input",
            placeholder: "手机号"
          }
        ]
      },
      // 分页参数
      pageing: { pageNum: 1, pageSize: 10, total: 10 },
      // 表格数据
      tableList: [],
      // 查询的数据条件
      searchFrom: {
        name: "",
        phonenumber: ""
      },

      bottomBtnShow: true, //底部按钮
      bottomBtnValue: "", //底部输入值

      // 渠道数组
      channelList: [],
      // 渠道数组
      channelfiler: []
    };
  },
  async mounted() {
    this.$refs.businessList.getCommercialManagerFn(this.organizationId);
    this.getcommercialManagerplaceListFn(this.organizationId); //获取表格数据 渠道
    this.getpersonListFn(); //渠道人员列表，显示在上级和上上级那里
  },
  watch: {
    organizationId(newValue, oldValue) {
      this.personing = { pageNum: 1, pageSize: 10, total: 10 };
      this.personnels = [];
      this.getpersonListFn(); //渠道人员列表，显示在上级和上上级那里
    }
  },
  computed: {
    // 获取上级和上上级名字
    getHigherLevelName() {
      return id => {
        return this.channelfiler.find(item => item.id == id)?.name;
      };
    },

    //过滤上级数组，要求数组中不可以有自己
    channelListSuperiorFiter(list, row) {
      // return (list, row) => list.filter((item) => item.id != row.id);
      return (list, row) => list.filter(item => item);
    },
    //过滤上上级数组，要求数组中不可以有自己(目前没有使用到)

    channelListLeaderFiter() {
      return (list, row) =>
        list.filter(item => {
          return item.id != row.id;
        });
    }
  },
  methods: {
    showButton() {
      this.buttonVissible = false;
    },
    // 修改邮箱
    async editWorkMail(row, attr) {
      switch (attr) {
        case "name":
          if (arr.includes(row.name)) return;
          this.$set(row, "isName", true);
          break;
        case "mailPwd":
          if (arr.includes(row.mailPwd)) return;
          this.$set(row, "isMailPwd", true);
          break;
        case "workMail":
          if (arr.includes(row.workMail)) return;
          this.$set(row, "isWorkMailEdit", true);
          break;
      }

      let { code, msg } = await getCommercialManagerEditApi(row);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg
      });
    },

    // 点击状态关闭或者开启
    async changeSwitch(row) {
      if (row.userCount && Number(row.userCount) > 0) {
        row.status = "0";
        this.$message({
          type: "warning",
          message: "该商务下有捆绑用户，请把用户重新分配后再操作"
        });
        return;
      }

      let { code, msg } = await getCommercialManagerEditApi(row);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg
      });
    },

    // 显示邮箱编辑输入框
    openEditWorkMail(row, attr) {
      switch (attr) {
        case "name":
          this.$set(row, "isName", false);
          break;
        // case "phonenumber":
        //   this.$set(row, "isEditPhonenumber", false);
        //   break;
      }
    },
    // 修改上级
    async editHigherLevelNameFn(item, row, isHigherLevel) {
      // row.higherLevelName = item.name;
      // 上级修改
      let id = this.personnelValue;
      // 找到这个item对应的name
      let obj = this.personnels.find(k => {
        return k.id == item;
      });
      if (isHigherLevel) {
        this.$set(row, "higherLevel", item);
        this.$set(row, "higherLevelName", obj.name);
        // row.higherLevel = item.id;
      } else {
        // 上上级修改
        // row.supervisorId = item.id;
        this.$set(row, "supervisorId", item);
        this.$set(row, "supervisorName", obj.name);
      }

      let { code, msg } = await getCommercialManagerEditApi(row);
      if (code != 200) return;
      this.$message({
        type: "success",
        message: msg
      });
    },

    // 查询函数
    inqiureFn([{ name = "" }, { phonenumber = "" }]) {
      const channelList = this.channelfiler;
      this.channelList = channelList.filter(item => {
        item.isName = arr.includes(item.name) ? false : true;

        return (
          item?.name?.includes(name) && item?.phonenumber?.includes(phonenumber)
        );
      });
    },

    // 查询渠道回调
    searchRefFn([{ name = "" }, { phonenumber = "" }]) {
      this.searchFrom.name = name;
      this.searchFrom.phonenumber = phonenumber;
      this.getcommercialManagerplaceListFn(this.organizationId); //查询接口
    },

    // 添加商务
    addReset() {
      this.addObj = {
        // name: "",
        organizationId: "",
        phonenumber: "",
        type: 2
      };
      this.buttonVissible = true;
    },
    async addBusiness() {
      const addObj = this.addObj;
      if (!/^1[3456789]\d{9}$/.test(addObj.phonenumber)) {
        this.$message({
          type: "warning",
          message: "手机号不合法"
        });
        return;
      }
      // if (addObj.name == "") {
      //   this.$message({
      //     message: "名字不可为空",
      //     type: "warning",
      //   });
      //   return;
      // }
      // 获取组织id
      addObj.organizationId = this.organizationId;
      let { code, msg } = await getCommercialManageraddApi(addObj);
      this.buttonVissible = true;
      if (code != 200) return;
      // 清空
      this.addReset();
      this.getcommercialManagerplaceListFn(this.organizationId);  //获取表格数据 渠道
      // 重置数据
      this.personing = { pageNum: 1, pageSize: 10, total: 10 };
      this.personnels = [];
      this.getpersonListFn(); //渠道人员列表，显示在上级和上上级那里
      this.$message({
        message: msg,
        type: "success"
      });
    },

    // 获取所有渠道
    async getcommercialManagerplaceListFn(organizationId) {
      const { pageNum, pageSize } = this.pageing;
      let { code, rows, total } = await getcommercialManagerplaceListAllApi({
        organizationId,
        pageNum,
        pageSize,
        name: this.searchFrom.name,
        phonenumber: this.searchFrom.phonenumber
      });
      this.pageing.total = total;
      const channelList = JSON.parse(JSON.stringify(rows));
      console.log(channelList);
      this.channelList = channelList.map(item => {
        item.isEditPhonenumber = arr.includes(item.phonenumber) ? false : true;
        item.isName = arr.includes(item.name) ? false : true;
        return item;
      });
      this.channelList = channelList;
      this.channelfiler = JSON.parse(JSON.stringify(rows));

      if (code != 200) return;
    },

    // 获取所有人员列表 用在上级和上上级那里
    async getpersonListFn() {
      let { pageNum, pageSize } = this.personing;
      let organizationId = this.organizationId;
      let data = {
        organizationId: this.organizationId,
        pageNum: pageNum,
        pageSize: pageSize
      };
      let { code, rows, total } = await getcommercialManagerplaceListAllApi(
        data
      );
      this.personing.total = total;
      const channelList = JSON.parse(JSON.stringify(rows));

      channelList.forEach(item => {
        this.personnels.push({
          name: item.name,
          id: item.id
        });
      });
    },

    // 选择上级和上上级 滚动到底部的时候
    superiorMore() {
      if (this.personnels.length >= this.personing.total) return;
      this.personing.pageNum++;
      this.getpersonListFn(); // 获取所有人员列表 用在上级和上上级那里
    },

    // 改变组织id
    changeOrganizationId(organizationId) {
      this.$emit("update:organizationId", organizationId);
    },

    // 组织选择发生
    organizationSelectChange(organizationId) {
      this.changeOrganizationId(organizationId);
      this.pageing = { pageNum: 1, pageSize: 10, total: 10 };
      // 重新获取商务、渠道
      Promise.all([
        this.$refs.businessList.getCommercialManagerFn(organizationId),
        this.getcommercialManagerplaceListFn(organizationId)
      ]);
    },
    // // 获取组织列表
    // async getlabelOrganizationFn() {
    //   let { code, rows } = await getlabelOrganizationApi();
    //   if (code != 200) return;
    //   this.organizationList = JSON.parse(JSON.stringify(rows));
    //   this.organizationId = this.organizationList[0]?.id;
    // },
    // 查找渠道
    // async getPlaceGetInfoFn() {
    //   let { code, rows } = await getPlaceGetInfoApi();
    // },
    async getPlaceListFn() {
      let { code, rows } = await getPlaceListApi();
      if (code != 200) return;
      this.placeList = JSON.parse(JSON.stringify(rows));
    },

    // 点击添加渠道
    clickbBtn() {
      //显示输入框
      this.bottomBtnShow = false;
      //输入框自动获取焦点
      this.$nextTick(() => {
        this.$refs.bottBtn.focus();
      });
    },
    //输入框按回车的回调
    addChannel() {
      if (this.bottomBtnValue) {
        //隐藏输入框
        this.bottomBtnShow = true;
        this.bottomBtnValue = "";
      } else {
        this.$message({ type: "warning", message: "请输入材料名称" });
      }
    },

    // 表格总计行的规则 ****************
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (["higherLevel", "supervisorId"].includes(column.property)) {
          sums[index] = "--";

          return;
        }

        const values = data.map(item => {
          // console.log(column.property);
          // console.log(item[column.property]);
          return Number(item[column.property]);
        });
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = "--";
        }
        if (index === 3) {
          sums[index] = this.$options.filters["sumFilters"](sums[index]);
          return;
        }
      });

      return sums;
    },
    // 表格总计行的规则 **************** end
    handleCurrentChange(pageNum) {
      this.pageing.pageNum = pageNum;
      this.getcommercialManagerplaceListFn(this.organizationId);
    },
    // 页容量发生改变
    handleSizeChange(pageSize) {
      this.pageing.pageSize = pageSize;
      this.getcommercialManagerplaceListFn(this.organizationId);
    }
  },
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function() {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.entity-org {
  height: 100%;
}
::v-deep .entity-main .el-card {
  position: relative;
}
::v-deep .entity-main .el-card__body {
  height: 100%;
}
::v-deep .entity-main .el-card__body > div {
  height: 92%;
  overflow-y: auto;
}
::v-deep .entity-main .el-card__body > div::-webkit-scrollbar {
  width: 0;
}

/* 选择器 */
.mateCascader {
  /* height: 6%; */
  margin-bottom: 20px;
}
::v-deep .mateCascader .el-select {
  padding: 0 10px;
  border-radius: 8px;
  width: 320px;
  background-color: #f5f6f8;
}
::v-deep .mateCascader .el-select .el-input__inner {
  border: 0;
  background-color: transparent;
  padding-left: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2e3f5e;
}
::v-deep .mateCascader .el-select .el-select__caret {
  color: #2e3f5e;
}
::v-deep .mateCascader .el-select .el-select__caret:before {
  content: "\E78F";
}
.el-select-dropdown .el-select-dropdown__item.selected {
  color: #f87a23;
}
//分页
.pagination {
  text-align: center;
  margin-bottom: 70px;
}
/* 内容区 */
.entity-main {
  height: calc(100% - 60px);
}
.entity-main .el-row {
  height: 100%;
}
::v-deep .entity-main .el-form .el-input--medium {
  width: 100px !important;
}
::v-deep .entity-main .el-form .el-button--default {
  display: none;
}
/* 表格样式 */
.el-table {
  margin-bottom: 10px;
}
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #fff;
}
::v-deep .el-table th.is-leaf {
  border-top: 1px solid #efefef;
  border-bottom: 1px solid #efefef;
}
::v-deep .el-table th > .cell {
  font-size: 12px;
  color: #909aaa;
}
::v-deep .el-table .cell,
::v-deep .el-table .cell p {
  margin: 0;
  font-size: 14px;
  color: #2e3f5e;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
::v-deep .el-table .cell .el-button {
  color: #f87a23;
}
::v-deep .el-table .cell .el-table__expand-icon i::before {
  content: "\E791";
}
::v-deep .el-table td {
  /* border-bottom: 0; */
}
::v-deep .el-table td .islight {
  color: #f87a23;
}
::v-deep .el-table .el-table__expanded-cell[class*="cell"] {
  padding: 0;
}
::v-deep .el-table__expanded-cell .el-table::before {
  height: 0;
}
::v-deep .el-table__expanded-cell .el-table th.is-leaf {
  border-top: 0;
}
::v-deep .el-table__expanded-cell .el-table td {
  border-bottom: 0;
}

::v-deep .el-table__footer-wrapper tbody td {
  background-color: #fff;
  font-weight: bold;
  color: #2e3f5e;
}

.selsect-box {
  position: relative;
}
.selsect-box > p {
  position: relative;
}
.selsect-box .el-select {
  position: absolute;
  top: 0;
  z-index: 9;
  opacity: 0;
}

/* 添加材料 */
.bottomBtn {
  background-color: #f6f9f8;
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  left: 0;
  padding: 9px 10px;
  width: 100%;
  border-top: 1px solid #ecedf0;
  z-index: 9;
  .inputBox {
    // flex: 1;
    display: flex;
  }
  .buttonBox {
    ::v-deep .el-button--primary {
      background-color: #f87a23;
      border-color: #f87a23;
      color: #ffffff;
      width: 90px;
      // height: 40px;
      line-height: 34px;
      padding: 0;
      text-align: center;
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
    }
    ::v-deep .el-button--default {
      background-color: #ffffff;
      width: 90px;
      // height: 40px;
      line-height: 34px;
      padding: 0;
      text-align: center;
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #606e84;
    }

    /* // ::v-deep .el-button + .el-button {
    //   margin-left: 0px;
    // } */
  }
}

::v-deep .el-table .el-dropdown-link {
  color: unset;
}
.bottomBtn .el-button {
  width: 100%;
  border: 0;
  border-top: 1px solid #ecedf0;
  background-color: #f8f8f8;
  line-height: 25px;
  color: #606e84;
}
.bottomBtn .el-input {
  width: 100%;
  margin-right: 10px;
}
::v-deep .bottomBtn .el-input .el-input__inner {
  height: 36px;
  line-height: 36px;
  /* // border-top: 1px solid #ecedf0;
  // background-color: #f8f8f8; */
  // text-align: center;
}

.button-new-tag {
  position: absolute;
  bottom: 0;
  left: 0;
  border: 0;
  z-index: 2;
  display: block;
  width: 100%;
  font-size: 16px;
  padding: 15px 20px;
  background-color: #f8f8f8;
  border-top: 1px solid #e6ebf5;
}
</style>